package com.tim.app.ui.fragment.search;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.application.library.base.BaseFragment;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.EventTag;
import com.tim.app.server.logic.UserManager;
import com.tim.app.ui.activity.person_center.MyBrowseHistoryActivity;
import com.tim.app.ui.adapter.selceted.HistorySearchAdapter;
import com.tim.app.ui.view.SearchRecommandHeadView;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜索推荐
 */
public class SearchRecommandFragment extends BaseFragment implements View.OnClickListener, BaseRecyclerAdapter.OnItemClickListener {

    private static final String TAG = "SearchRecommandFragment";
    private View rootView;
    private WrapRecyclerView rvSearchHistory;

    private List<String> searchHistory;
    private HistorySearchAdapter historySearchAdapter;

    private SearchRecommandHeadView headView;

    private TextView footerView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_search_recommand, container, false);
            rvSearchHistory = (WrapRecyclerView) rootView.findViewById(R.id.wrvSearch);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

            footerView = new TextView(getActivity());

            WrapRecyclerView.LayoutParams params = new WrapRecyclerView.LayoutParams(WrapRecyclerView.LayoutParams.MATCH_PARENT, (int) getContext().getResources().getDimension(R.dimen.dimen_60));
            footerView.setLayoutParams(params);
            footerView.setGravity(Gravity.CENTER);
            footerView.setTextColor(getResources().getColor(R.color.text_desc_color));
            footerView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
            footerView.setText(RT.getString(R.string.clearSearchHistory));

            footerView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    EventManager.ins().sendEvent(EventTag.DO_CLEAR_SEARCH_HISTORY, 0, 0, null);
                }
            });

            rvSearchHistory.setLayoutManager(linearLayoutManager);
//            rvSearchHistory.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getActivity()).color(getResources().getColor(R.color.transparent)).size((int) getResources().getDimension(R.dimen.dimen_half)).build());
            rvSearchHistory.setOverScrollMode(View.OVER_SCROLL_NEVER);

            headView = (SearchRecommandHeadView) inflater.inflate(R.layout.search_recommand_head_view, null);
            headView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyBrowseHistoryActivity.start(getActivity());
                }
            });
            rvSearchHistory.addHeaderView(headView);

            searchHistory = new ArrayList<>();
            historySearchAdapter = new HistorySearchAdapter(getContext(), searchHistory);
            rvSearchHistory.setAdapter(historySearchAdapter);
            loadData();

            historySearchAdapter.setOnItemClickListener(this);
            EventManager.ins().registListener(EventTag.DO_DELETE_SEARCH_HISTORY, eventListener);
            EventManager.ins().registListener(EventTag.DO_ADD_SEARCH_HISTORY, eventListener);
            EventManager.ins().registListener(EventTag.DO_CLEAR_SEARCH_HISTORY, eventListener);
        }
        return rootView;
    }

    /**
     * 加载数据
     */
    private void loadData() {
        List<String> datas = UserManager.ins().getSearchHistory();
        if (null != datas && datas.size() > 0) {
            searchHistory.addAll(datas);
        }
        if (searchHistory.size() > 0) {
            rvSearchHistory.addFootView(footerView);
            rvSearchHistory.setAdapter(historySearchAdapter);
        }
        historySearchAdapter.notifyDataSetChanged();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.DO_DELETE_SEARCH_HISTORY, eventListener);
        EventManager.ins().removeListener(EventTag.DO_ADD_SEARCH_HISTORY, eventListener);
        EventManager.ins().removeListener(EventTag.DO_CLEAR_SEARCH_HISTORY, eventListener);
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    private EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            if (what == EventTag.DO_DELETE_SEARCH_HISTORY) {
                if (dataobj != null) {
                    int index = (int) dataobj;
                    searchHistory.remove(index);
                    historySearchAdapter.notifyDataSetChanged();
                    UserManager.ins().saveSearchHistory(searchHistory);
                    if (searchHistory.size() == 0) {
                        rvSearchHistory.removeFootView();
                    }
                }
            } else if (what == EventTag.DO_ADD_SEARCH_HISTORY) {
                searchHistory.clear();
                searchHistory.addAll(UserManager.ins().getSearchHistory());
                if (searchHistory.size() > 0) {
                    rvSearchHistory.addFootView(footerView);
                    rvSearchHistory.setAdapter(historySearchAdapter);
                }
                historySearchAdapter.notifyDataSetChanged();
            } else if (what == EventTag.DO_CLEAR_SEARCH_HISTORY) {
                searchHistory.clear();
                historySearchAdapter.notifyDataSetChanged();
                UserManager.ins().saveSearchHistory(searchHistory);
                rvSearchHistory.removeFootView();
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        if (null == searchHistory || position > searchHistory.size())
            return;
        String keyWord = searchHistory.get(position);
        EventManager.ins().sendEvent(EventTag.DO_SEARCH_BY_HISTORY, 0, 0, keyWord);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


}
